package com.conversationboard.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;

/**
 * Class to get a list of users who administer each board - one row is returned per user, per board they administer.
 * 
 * @author Keith Watson
 */

public class BoardAdmins {

	public static List<BoardAdmin> get() throws SQLException {

		List<BoardAdmin> boardAdmins = new LinkedList<BoardAdmin>();

		Connection connection = null;

		try {
			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.GET_BOARD_ADMINS);
			statement.execute();

			ResultSet resultSet = statement.getResultSet();

			while (resultSet.next()) {

				String loginId = resultSet.getString("loginid");
				BoardAdminList boards = new BoardAdminList(resultSet.getString("boards"));
				Set<Integer> boardRights = boards.getBoardAdminList();

				for (int boardId : boardRights) {
					BoardAdmin boardAdmin = new BoardAdmin();
					boardAdmin.setBoardId(boardId);
					boardAdmin.setLoginId(loginId);

					boardAdmins.add(boardAdmin);
				}

			}

			statement.close();

			Collections.sort(boardAdmins);

			return boardAdmins;

		} finally {
			Database.close(connection);
		}

	}


	public static void revokeAll(String loginId) throws SQLException {

		Connection connection = null;

		try {
			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.REVOKE_BOARD_PRIVILEGES);
			statement.setString(1, loginId);
			statement.executeUpdate();
			statement.close();

		} finally {
			Database.close(connection);
		}

	}

}
